package com.xx.util;

import com.xx.pojo.ConnectionParam;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionUtil {

    /**
     * 获得数据库连接
     *
     * @param param param
     * @return Connection
     * @throws ClassNotFoundException ClassNotFoundException
     * @throws SQLException           SQLException
     */
    public static Connection getConnection(ConnectionParam param) throws ClassNotFoundException, SQLException {
        Class.forName(param.getDriver());
        return DriverManager.getConnection(param.getUrl(), param.getUsername(), param.getPassword());
    }

    public static Connection getConnection(Properties properties) throws SQLException, ClassNotFoundException {
        /**
         * source.db.driver=com.mysql.jdbc.Driver
         * source.db.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
         * source.db.username=root
         * source.db.password=root
         */
        String driver = properties.getProperty("source.db.driver");
        String url = properties.getProperty("source.db.url");
        String username = properties.getProperty("source.db.username");
        String password = properties.getProperty("source.db.password");
        return getConnection(ConnectionParam.builder().driver(driver).url(url).username(username).password(password).build());
    }
}
